package com.lzy.config;

import lombok.Data;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.data.Stat;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@ConfigurationProperties(prefix = "zookeeper.curator")
@Data
public class CuratorConfig {

    private String host;                   // 单机/集群 ip:port
    private Integer connectionTimeoutMs;   // 连接超时的时间
    private Integer sessionTimeoutMs;      // 会话超时的时间
    private Integer sleepMsBetweenRetry;   // 每次重试间隔的时间
    private Integer maxRetries;            // 最大重试次数
    private String namespace;              // 命名空间(root根节点的名称)


    // Curator(Zookeeper)客户端
    @Bean("curatorClient")
    public CuratorFramework curatorClient() throws Exception {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(sleepMsBetweenRetry, maxRetries);

        // 声明初始化客户端
        CuratorFramework client = CuratorFrameworkFactory
                                    .builder()
                                    .connectString(host)
                                    .sessionTimeoutMs(sessionTimeoutMs)
                                    .connectionTimeoutMs(connectionTimeoutMs)
                                    .retryPolicy(retryPolicy)
                                    .namespace(namespace)
                                    .build();
        client.start();  //启动curator客户端
        return client;
    }
}

